<template>
  <div class="letter">
    <header class="letter-top clearfix">
        <span class="bdbox j-delSelect">
          <span>未读消息<span v-if="unread>0">（{{(unread)}}）</span></span>
        </span>
        <span class="bdbox j-readSelect" @click="clickReadLetter">
          <span><i></i>清除未读</span>
        </span>
    </header>
    <main>
      <van-list v-model="loading"
        :finished="finished"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text=""
        @load="onLoad"
        v-show="list.length">
        <section v-for="(item, index) in list" :key="index" 
            class="msg-item" :class="{'hide' : item.txtShow}" 
            @click="goLetterDetail('letterDetail', item)">
            <p class="msg-title">
              <span class="title">消息通知</span>
              <span class="date">{{item.send_time}}<i class="unread-tag" :class="{'read-tag' : item.status == 1}"></i></span>
            </p>
            <div class="msg-content true-dom" :id=item.message_id ref="textContainer" v-html="item.content">
              <!-- {{item.content}} -->
            </div>
            <p class="btn" v-if="item.txtShow">查看详情</p>
          </section>
          <section class="msg-content pip-dom" style="position: fixed; left: -9999px;" ref="more">
          真正渲染出一行的高度，不能删除。
          </section>
      </van-list>
      <no-data v-show="!list.length && finished" :noData="noData"></no-data>
    </main>
  </div>
</template>

<script>
import Vue from 'vue'
import noData from '@/components/noData/index'
import 'vant/lib/index.css'
import { openPage } from '@/utils/utils'
import { List } from 'vant'
import { getLetter, readLetter, delLetter } from '@/api/user/letter'

Vue.use(List)
export default Vue.extend({
  components: {
    noData
  },
  data() {
    return {
      noData: {
        img: 'https://img.wifenxiao.com/h5-wfx/images/no_order.png',
        text: '暂无站内信',
        marginTop: '60px'
      },
      p: 1,
      unread: 0,
      error: false,
      loading: false,
      finished: false,
      result: [],
      list: []
    }
  },
  created() {
    this.init()
  },
  mounted() {
    // 小程序触底加载更多
    window.addEventListener('reachbottom', () => {
      // console.log('letter reachbottom')
      this.onLoad()
    })
  },
  methods: {
    init() {
      this.p = 1
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)

      const data = { p: this.p }
      getLetter(data)
        .then(res => {
          this.loading = false
          this.$loadingWrap.close()
          if (res.status == 1) {
            if (res.data.list.length) {
              this.unread = res.data.unread
              this.list = res.data.list
              this.$nextTick(() => {
                this.calculateText(this.list)
              })
              this.p++
            } else {
              this.list = []
              this.unread = 0
              this.finished = true
            }
          }
        })
        .catch(() => {
          this.error = true
        })
    },
    onLoad() {
      const data = { p: this.p }
      getLetter(data)
        .then(res => {
          this.loading = false
          if (res.status == 1) {
            if (res.data.list.length) {
              this.unread = res.data.unread
              this.list.push(...res.data.list)
              this.$nextTick(() => {
                this.calculateText(res.data.list)
              })
              this.p++
            } else {
              this.finished = true
            }
          }
        })
        .catch(() => {
          this.error = true
        })
    },
    // 标记为已读
    clickReadLetter() {
      if (this.unread != 0) { // 有未读消息
        const id = []
        this.$loadingWrap.show()
        setTimeout(() => {
          this.$loadingWrap.close()
        }, 10000)
        readLetter({ id }).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            this.$Error('操作成功')
            this.init()
          } else {
            this.$Error('操作失败')
          }
        })
      } else { // 没有未读消息
        this.$Error('暂无未读消息')
      }
    },
    // 删除
    clickDelLetter() {
      const id = []
      this.result.find((val, index) => {
        const idx = this.list.findIndex(item => {
          return item.message_id == val
        })
        if (idx != -1) id.push(val)
      })
      if (id.length <= 0) {
        this.$Error('请选择需要删除的信息')
        return false
      }
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      delLetter({ id }).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          this.$Error('删除成功')
          this.init()
        } else {
          this.$Error('操作失败')
        }
      })
    },
    // 计算是否超出三行
    calculateText(list) {
      // 获取一行文字的height 计算当前文字比较列表文字
      let pipHeight = 0
      document.querySelector('.pip-dom').$$getBoundingClientRect().then((res) => {
        pipHeight = res.height
        var domList = document.querySelectorAll('.true-dom')
        if (domList && domList.length) {
          domList.forEach(dom => {
            list.forEach(item => {
              if (item.message_id == dom.id) {
                dom.$$getBoundingClientRect().then(res => {
                  const trueDomHeight = res.height
                  if (trueDomHeight > pipHeight * 3) { // 超过3行
                    this.$set(item, 'txtShow', true)
                  } else { // 没超过3行
                    this.$set(item, 'txtShow', false)
                  }
                })
              }
            })
          })
        }
      })
    },
    // 跳转消息详情
    async goLetterDetail(url, data) {
      if (data.status == 0) { // 未读消息变为已读
        const id = []
        id.push(data.message_id)
        await readLetter({ id })
      }
      if (data.redirect_url) {
        openPage(data.redirect_url)
      } else {
        this.$JumpPath(this, url, {id: data.message_id})
      }
    }
  }
})
</script>
<style lang="scss">
@import "src/styles/variables";
.letter {
  .letter-top {
    display: flex;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100px;
    background: $default;
    z-index: 10;
    padding: 0 36px;
    .bdbox {
      display: flex;
      justify-content: center;
      align-items: center;
      line-height: 100px;
      text-align: center;
      width: 50%;
      &.j-delSelect{
        justify-content: flex-start;
        font-size: 30px;
        color: #333333;
        font-size: 500;
      }
      &.j-readSelect{
        font-size: 28px;
        color: #666666;
        justify-content: flex-end;
      }
      i{
        position: relative;
        top: 6px;
        margin-right: 6px;
        display: inline-block;
        width: 32px;
        height: 32px;
        background: url('https://img.wifenxiao.com/h5-wfx/images/letter/letter-edit-icon.png') no-repeat;
        background-size: 100%;
      }
    }
  }
  main {
    padding: 122px 24px 60px;
     .msg-item{
      padding: 20px 0 24px;
      margin-bottom: 20px;
      border-radius: 8px;
      background: #ffffff;
      &.hide{
        padding-bottom: 0;
        .msg-content{
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 3;
          overflow: hidden;
        }
      }
      .msg-title{
        padding: 0 32px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .title{
          font-size: 30px;
          color: #3d3d3d;
          font-weight: 500;
        }
        .date{
          display: flex;
          align-items: center;
          font-size: 24px;
          color: #8d8d8d;
          .unread-tag{
            display: inline-block;
            margin-left: 12px;
            width: 12px;
            height: 12px;
            background: #FF0A31;
            border-radius: 50%;
            &.read-tag {
              background: #ffffff;
            }
          }
        }
      }
      .btn{
        margin-top: 34px;
        padding: 16px 0 14px;
        text-align: center;
        font-size: 24px;
        color: #FE4C4C;
        font-weight: 500;
        border-top: 2px solid #f2f2f2;
      }
    }
    .msg-content{
      padding: 0 32px;
      font-size: 26px;
      color: #7c7c7c;
      margin-top: 12px;
      line-height: 44px;
      word-wrap: break-word;
      word-break: break-all;
    }
  }
}
</style>